from django.shortcuts import render, get_object_or_404
from .models import Post, Tag, Category
import markdown
import re
from django.utils.text import slugify
from markdown.extensions.toc import TocExtension


def index(req):
    ls = Post.objects.all()
    return render(req, 'blog/index.html', context={
        'title': '我的博客',
        'postlist': ls
    })


def detail(req, pk):
    """
    文章详情
    :param req:
    :param pk:文字id
    """
    post = get_object_or_404(Post, pk=pk)
    # post.body = markdown.markdown(post.body,
    #                               extensions=[
    #                                   'markdown.extensions.extra',
    #                                   'markdown.extensions.codehilite',
    #                                   'markdown.extensions.toc',
    #                               ])
    # 在侧边显示目录
    md = markdown.Markdown(extensions=[
        'markdown.extensions.extra',
        'markdown.extensions.codehilite',
        # 记得在顶部引入 TocExtension 和 slugify
        TocExtension(slugify=slugify),
    ])
    post.body = md.convert(post.body)

    m = re.search(r'<div class="toc">\s*<ul>(.*)</ul>\s*</div>', md.toc, re.S)
    post.toc = m.group(1) if m is not None else ''

    return render(req, 'blog/detail.html', context={'post': post})


def archives(req, year, month):
    """
    归档,按年月
    """
    ls = Post.objects.filter(created_time__year=year, created_time__month=month).order_by('-created_time')
    return render(req, 'blog/index.html', context={
        'postlist': ls
    })


def tags(req, pk):
    """
    标签
    """
    t = get_object_or_404(Tag, pk=pk)
    ls = Post.objects.filter(tags=t).order_by('created_time')
    return render(req, 'blog/index.html', context={
        'postlist': ls
    })


def cate(req, pk):
    """
    标签
    """
    t = get_object_or_404(Category, pk=pk)
    ls = Post.objects.filter(category=t).order_by('created_time')
    return render(req, 'blog/index.html', context={
        'postlist': ls
    })
